package com.dailyblue.java.project.estate.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.JwtConfig;
import com.dailyblue.project.estate.commons.util.ResultCode;
import com.dailyblue.project.estate.commons.util.ResultTool;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class CheckLoginGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 排除登陆
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().toString();
        if (path.contains("/login?")) {
            return chain.filter(exchange);
        }
        // 判断是否登陆了
        List<String> tokens = request.getHeaders().get("token");
        // 没有携带token
        if (tokens == null || tokens.size() == 0) {
            return error(exchange, ResultTool.fail(ResultCode.USER_NOT_LOGIN));
        }
        // 判断token是否合法
        String token = tokens.get(0);
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return error(exchange, ResultTool.fail(ResultCode.USER_NOT_LOGIN));
        }
        Claims claims = JwtConfig.parseJWT(token);
        String id = claims.get("id").toString();
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String redisToken = values.get("token:" + id);
        if (!redisToken.equals(token)) {
            return error(exchange, ResultTool.fail(ResultCode.USER_NOT_LOGIN));
        }
        return chain.filter(exchange);
    }

    private Mono<Void> error(ServerWebExchange exchange, JsonResult result) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
